package com.liry.custommvc;

import com.liry.custommvc.config.CustomMvcAutoConfig;
import java.util.Set;
import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;
import org.apache.catalina.core.ApplicationContextFacade;
import org.apache.jasper.servlet.JspServlet;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * custom mvc 初始化类
 *
 * @author ALI
 * @since 2022/10/5
 */
public class InitMvc implements ServletContainerInitializer {

    /** 项目的前缀(项目名称) */
    public static final String context_path = "/custom_springmvc_war";

    @Override
    public void onStartup(Set<Class<?>> set, ServletContext servletContext) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(
            CustomMvcAutoConfig.class);

        // 添加自定义的前端控制器
        DispatcherServlet dispatcherServlet = new DispatcherServlet(applicationContext);
        ServletRegistration.Dynamic servlet = ((ApplicationContextFacade) servletContext).addServlet("servlet",
                                                                                                     dispatcherServlet);

        // 设置加载
        servlet.setLoadOnStartup(1);
        servlet.addMapping("*.html");

        // 这里没有用web.xml所以要添加jsp解析
        // jsp解析器，
        JspServlet jspServlet = new JspServlet();
        ServletRegistration.Dynamic jsp = ((ApplicationContextFacade) servletContext).addServlet("jspServlet",
                                                                                                 jspServlet);
        jsp.setLoadOnStartup(2);
        jsp.addMapping("*.jsp");

    }
}
